//
//  ChannelTableViewController.m
//  AriseSamePro
//
//  Created by 包日守 on 15/10/23.
//  Copyright © 2015年 Arise. All rights reserved.
//

#import "ChannelTableViewController.h"
#import "ARGlobalInterface.h"
#import "AFNetworking.h"

#import "ARCate5Model.h"

#import "ARCate5Cell.h"

#import "ARChannelTableViewFactory.h"

@interface ChannelTableViewController ()
@end

@implementation ChannelTableViewController

- (ARChannelInfoModel *)channelInfoModel
{
    if (_channelInfoModel == nil) {
        _channelInfoModel = [[ARChannelInfoModel alloc] init];
    }
    return _channelInfoModel;

}

- (void)viewDidDisappear:(BOOL)animated
{
    [self loadDataInServerComplete];
    
    [self saveOrUpData];

}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self createNavigationWithChannel];
    
    
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:[ARGlobalInterface channelDetailChacheURLWithID:self.index]] && [[NSFileManager defaultManager] fileExistsAtPath:[ARGlobalInterface channelSensesCacheURLWithID:self.index]]) {
        
        
        [self loadDataInCache];
        
        
    }
    else
     
    {
        [self loadDataInServer];
    
    }
    //self.canLoadMore = YES;
    
  [self loadOnlineCount];
    
    
}

//对数据进行上传 或者保存
- (void)saveOrUpData
{

}

- (void)loadOnlineCount
{
    NSString *onlineCountURL = [ARGlobalInterface channelOnlineCountServerURLWithID:self.index];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:onlineCountURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSNumber *count = dict[@"data"][@"count"];
        
        
        self.rightView.count = [count intValue];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - superMethe


- (void) loadDataInCache
{
    //清空数据
    _channelInfoModel = nil;
    _cateModels = nil;
    
    
    NSData *data = [NSData dataWithContentsOfFile:[ARGlobalInterface channelDetailChacheURLWithID:self.index]];
    
    
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    [self.channelInfoModel setValuesForKeysWithDictionary:dict[@"data"]];
    
    data = [NSData dataWithContentsOfFile:[ARGlobalInterface channelSensesCacheURLWithID:self.index]];
    
    
    //过滤掉一些未知的网络数据 或者空的data数据 防止程序崩溃
    if (data == nil) {
        return;
    }
    
    dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    self.nextURL = dict[@"data"][@"next"];
    NSArray *array = dict[@"data"][@"results"];
    NSMutableArray *marray = [NSMutableArray array];
    for (NSDictionary *dicts in array) {
        ARCate5Model *model = [[ARCate5Model alloc] init];
        [model setValuesForKeysWithDictionary:dicts];
        [marray addObject:model];
    }
    
    self.cateModels = marray;
    
    
    
    
    
}
- (void) loadDataInServer
{
    
    self.initialized = 0;
    
    NSString *deatilURL = [ARGlobalInterface channelDetailServerURLWithID:self.index];
    NSString *sensesURL = [ARGlobalInterface channelSensesServerURLWithID:self.index];
    NSLog(@"%@",deatilURL);
    NSLog(@"%@",sensesURL);
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:deatilURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *data = responseObject;
        
        [data writeToFile:[ARGlobalInterface channelDetailChacheURLWithID:self.index] atomically:YES];
        
        
        if (++ self.initialized == 2) {
            [self loadDataInCache];
            [self loadDataInServerComplete];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
    [manager GET:sensesURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *data = responseObject;
        [data writeToFile:[ARGlobalInterface channelSensesCacheURLWithID:self.index] atomically:YES];
        
        if (++ self.initialized == 2) {
            [self loadDataInCache];
            [self loadDataInServerComplete];
        }
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
    
}



- (void)loadDataMore
{
    
    
    self.ac.hidden = NO;
    [self.ac startAnimating];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   // NSLog(@"%@",[ARGlobalInterface channelMoreSensesServerURLWithID:self.nextURL]);
    
    [manager GET:[ARGlobalInterface channelMoreSensesServerURLWithID:self.nextURL] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *marray = [NSMutableArray arrayWithArray:self.cateModels];
        
        
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        self.nextURL = dict[@"data"][@"next"];
        NSArray *array = dict[@"data"][@"results"];
        
        for (NSDictionary *dicts in array) {
            ARCate5Model *model = [[ARCate5Model alloc] init];
            [model setValuesForKeysWithDictionary:dicts];
            [marray addObject:model];
        }
        
        self.cateModels = marray;
        
        [self loadDataInServerComplete];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
}


#pragma mark - NavigationBar
- (void)onRightButtonClick
{
    NSLog(@"a");
    
}

#pragma mark - Table view data source


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ARCate5Model *model = self.cateModels[indexPath.section];
    
    if ([model.channelModel.cate isEqualToString:@"5"]) {
        CGFloat w = [UIScreen mainScreen].bounds.size.width - 32;
        
        
        CGRect centextRect = [model.txt boundingRectWithSize:CGSizeMake(w, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];
        
        return centextRect.size.height + 200;
    }
    
    return 44;
    
    


}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.cateModels.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.cate isEqualToString:@"5"]) {
        ARCate5Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cate5CellID" forIndexPath:indexPath];
        
        // Configure the cell...
        cell.cateModel = self.cateModels[indexPath.section];
        
        [cell setChannelButtonClick:^(ARCate5Model *cateModel) {
            
            ChannelTableViewController *channelVC = [ARChannelTableViewFactory channelTableViewWithCate:cateModel.mediaModel.channelModel.cate WithTitle:cateModel.mediaModel.channelModel.name WithIndex:cateModel.mediaModel.channelModel.index];
            
            
            [self.navigationController pushViewController:channelVC animated:YES];
            
        }];
        
        
        [cell setShareBtnBlock:^(ARCate5Model *cateModel,UIButton *sender) {
            
            [self createShare:cateModel WithSender:sender];
            
        }];
        
        
        return cell;
    }

    return nil;
}


- (void) createShare:(ARCate5Model *) cateModel WithSender :(UIButton *) sender
{
    self.shareCate = cateModel;
    
    
    //iOS8下使用UIAlertController
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
    if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"频道分享" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        int i = -1;
        for (NSString *snsName in [UMSocialSnsPlatformManager sharedInstance].allSnsValuesArray) {
            i ++;
            if  (i == 1 || i == 4|| i == 5||i == 6 || i == 7 || i == 8||i == 10 || i == 11) {
                continue;
            }
            
            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:snsName];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:snsPlatform.displayName style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                //设置分享内容，和回调对象
                NSString *shareText = cateModel.txt;
                //UIImage *shareImage = [UIImage imageNamed:@"UMS_social_demo"];
                
                [[UMSocialControllerService defaultControllerService] setShareText:shareText shareImage:nil socialUIDelegate:self];
                UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:snsName];
                snsPlatform.snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
            }];
            [alertController addAction:alertAction];
            
        }
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:cancelAction];
        UIPopoverPresentationController *popover = alertController.popoverPresentationController;
        if (popover)
        {
            popover.sourceView = sender;
            popover.sourceRect = sender.bounds;
            popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
        }
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
#endif
        UIActionSheet * editActionSheet = [[UIActionSheet alloc] initWithTitle:@"图文分享" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        int i = -1;
        for (NSString *snsName in [UMSocialSnsPlatformManager sharedInstance].allSnsValuesArray) {
            
            i ++;
            if (i == 1 || i == 4|| i == 5||i == 6 || i == 7 || i == 8||i == 10 || i == 11) {
                continue;
            }
            
            
            
            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:snsName];
            
            [editActionSheet addButtonWithTitle:snsPlatform.displayName];
            
            
            
        }
        [editActionSheet addButtonWithTitle:@"取消"];
        editActionSheet.tag = kTagShareEdit;
        [editActionSheet showFromTabBar:self.tabBarController.tabBar];
        editActionSheet.delegate = self;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
    }
#endif
    
    
    
    
    
    
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    if (buttonIndex + 1 >= actionSheet.numberOfButtons ) {
        return;
    }
    // NSLog(@"click button index is %ld",buttonIndex);
    //分享编辑页面的接口,snsName可以换成你想要的任意平台，例如UMShareToSina,UMShareToWechatTimeline
    
    int index = 0;
    if (buttonIndex == 0) {
        index = 0;
        
    }else if (buttonIndex == 1)
    {
        index = 2;
    }
    else if (buttonIndex == 2)
    {
        index = 3;
    }
    else if (buttonIndex == 3)
    {
        index = 9;
    }
    NSString *snsName = [[UMSocialSnsPlatformManager sharedInstance].allSnsValuesArray objectAtIndex:index];
    NSString *shareText = self.shareCate.txt;
    
    
    if (actionSheet.tag == kTagShareEdit) {
        //设置分享内容，和回调对象
        [[UMSocialControllerService defaultControllerService] setShareText:shareText shareImage:nil socialUIDelegate:self];
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:snsName];
        snsPlatform.snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    } else if (actionSheet.tag == kTagSharePost){
        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[snsName] content:shareText image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity * response){
            if (response.responseCode == UMSResponseCodeSuccess) {
                UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"分享成功" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
                [alertView show];
            } else if(response.responseCode != UMSResponseCodeCancel) {
                UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"失败" message:@"分享失败" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
                [alertView show];
            }
        }];
    }
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
